package com.vuestart.shushan.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.vuestart.common.utils.HttpUtils;
import com.vuestart.common.utils.R;
import com.vuestart.shushan.auth.feign.MemberFeignService;
import com.vuestart.common.vo.MemberRespVo;
import com.vuestart.shushan.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 * @创建：--> DKD <--
 * @日期：2021-04-21 16:30
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {

        Map<String, String> map = new HashMap<>();
        map.put("client_id", "YOUR_CLIENT_ID"); // --->
        map.put("client_secret", "YOUR_CLIENT_SECRET"); // --->
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.shushan.com/oauth2.0/weibo/success");
        map.put("code", code);

        // 1根据code 换取 accessToken
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", null, null, map);

        //2 处理
        if(response.getStatusLine().getStatusCode() == 200) {
            // 获取到了token
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            // 知道当前是哪个社交用户
            // 如果是第一次登录，就自动注册进来，为当前社交用户生成会员信息账号
            // 判断登录或注册
            R oauthlogin = memberFeignService.oauthlogin(socialUser);
            if (oauthlogin.getCode() == 0) {

                MemberRespVo data = oauthlogin.getData("data", new TypeReference<MemberRespVo>() {
                });
//                System.out.println("用户信息"+ data);
                log.info("用户信息 {}", data.toString());
                session.setAttribute("loginUser", data); // spring-session 存入redis中
                // 需要解决子域session共享，使用json的序列化
                // 3登录成功，跳回首页
                return "redirect:http://shushan.com";


            }else {
                return "redirect:http://auth.shushan.com/login.html";
            }
        }else {
            return "redirect:http://auth.shushan.com/login.html";
        }
    }
}
